Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
I am getting "undefined" while adding charcters in my array in javascript

Here is my code can someone just explain why I am getting undefined?? I have split the words and then reverse them and after reversing I tried to store them in a different array. Thank you

const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");

let words = text.innerHTML.split("").reverse();
console.log(words);
let reversedWords = [];
let counter = 0;
for (var i = 0; i <= words.length - 1; i++) {
  if (words[i] != " ") {
    reversedWords[counter] += words[i];
  } else {
    counter++;
  }
}
console.log(reversedWords);
<p id="text">hello nixit</p>
<p id="reverseText"></p>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your issue is that the first time you try and access reversedWords[counter], it is undefined because you've initialised reversedWords to be an empty array.

Without changing much of your code (because you said you're doing it this way as a challenge), you could try initialising reversedWords to have the appropriate number of elements, initialised to empty strings

const content = text.textContent;
const words = content.split("").reverse();
const reversedWords = Array.from({ length: content.split(" ").length }, () => "");
about 4 years ago · Juan Pablo Isaza Denunciar

0

You're using an array so you need to push things into it, and then join it up into a new string once the iteration is done.

const text = document.querySelector('#text');
const reverseText = document.querySelector('#reverseText');

function reverse(str) {

  // `split` the string on the spaces
  const words = str.split(' ');

  const reversedWords = [];

  for (let i = 0; i < words.length; i++) {

    // For each word split, reverse, and then rejoin it
    const word = words[i].split('').reverse().join('');

    // And then add the word to the array
    reversedWords.unshift(word);
  }

  // Return the completed array
  return reversedWords;
}

const str = text.textContent;
reverseText.textContent = JSON.stringify(reverse(str));
<p id="text">hello nixit</p>
<p id="reverseText"></p>

Additional documentation

  • unshift
about 4 years ago · Juan Pablo Isaza Denunciar

0

I suggest using a string instead of an array. Then you can split it to turn it into an array.

const reversedChars = 'hello nixit'.split("").reverse()

const reversedWords = ''

reversedChars.forEach(char => {
    reversedWords += char
})

const reversedWordsArray =  reversedWords.split(' ')

console.log(reversedWords)
// Output: tixin olleh
console.log(reversedWordsArray)
// Output: [ 'tixin', 'olleh' ]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda